using System.Linq;
using System.Web.Mvc;
using log4net;
using Pixster.Controllers.Helpers;
using Pixster.Models;

namespace Pixster.Controllers
{
    public class DirectoryController : Controller
    {
        private static readonly ILog LOG = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public ActionResult Index(string directory)
        {
            if (string.IsNullOrEmpty(directory))
            {
                LOG.Info("Directory is null, returning to homepage.");
                return RedirectToAction("Index", "Home");
            }

            var sitemap = ManifestHelper.Sitemap;

            if (sitemap == null)
            {
                LOG.Info("Sitemap is null, returning to homepage.");
                return RedirectToAction("Index", "Home");
            }

            var dir = sitemap.Where(d => d.SeoName.Equals(directory)).SingleOrDefault();

            if (dir == null || dir.Albums == null)
            {
                LOG.InfoFormat("Cannot find Directory '{0}' or it has no Albums, returning to homepage.", directory);
                return RedirectToAction("Index", "Home");
            }

            return View(new PixsterViewModel {Sitemap = sitemap, CurrentDirectory = dir});
        }
    }
}